<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
      </div>
      <div class="table_searchs flex">
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- table -->
    <el-table stripe :data="browserTable" style="width: 100%" :key="key" border fit highlight-current-row ref="tableDataRef">
      <el-table-column v-if="colData[0].istrue" prop="app_name" label="名称" min-width="100" align="center"></el-table-column>
      <el-table-column v-if="false" prop="type" label="平台" min-width="80" align="center">
        <template slot-scope="scope">{{scope.row.type ==1  ? 'MTK平台' : '展锐平台'}}</template>
      </el-table-column>

      <el-table-column v-if="colData[1].istrue" prop="nameCode" label="型号" min-width="120" align="center"> </el-table-column>

      <el-table-column prop="sn_five" label="sn第五位" min-width="70" align="center"></el-table-column>
      <el-table-column v-if="colData[2].istrue" prop="package" label="应用包名" min-width="170" align="center"></el-table-column>
      <el-table-column v-if="colData[3].istrue" prop="version_name" label="版本号" min-width="80" align="center"></el-table-column>
      <el-table-column v-if="colData[4].istrue" prop="version_code" label="内部版本号" min-width="100" align="center"></el-table-column>
      <el-table-column v-if="colData[5].istrue" prop="url" label="下载地址" min-width="180" align="center">
        <template slot-scope="scope">
          <div class="flex flex_cen">
            <input type="text" class="site_inputs" :value="scope.row.url" />
            <i class="el-icon-share download"><a target="_blank" :href="scope.row.url"></a></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[6].istrue" prop="desc" label="更新描述" min-width="140" align="center"></el-table-column>
      <el-table-column v-if="colData[7].istrue" prop="size" label="应用大小" min-width="80" align="center">
        <template slot-scope="scope">
          {{scope.row.size| zhDate}}
        </template>
      </el-table-column>
      <el-table-column v-if="colData[8].istrue" prop="createtime" label="更新时间" min-width="140" align="center">
        <template slot-scope="scope">{{scope.row.createtime| newDate}}</template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdAppUpdate(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="getappUpdateDel(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination background @size-change="handleSizeChange" :current-page.sync="listQuery.startSize" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 添加 -->
    <el-dialog :title="editSubjects ? '添加' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt">
        <el-form-item label="平台:" label-width="100px" prop="type" v-if="false">
          <el-radio-group v-model="addForm.type" >
            <el-radio :label="1">MTK平台</el-radio>
            <el-radio :label="2">展锐平台</el-radio>
            <el-radio :label="3">安卓11展锐平台</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="型号:" label-width="100px" prop="name_code">
          <el-select v-model="addForm.sn_three_four" placeholder="请选择" filterable>
            <el-option
              v-for="item in nameCodeOptions"
              :key="item.name_code"
              :label="item.name"
              :value="item.name_code"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="sn第五位:" label-width="100px">
          <el-select v-model="addForm.sn_five" placeholder="请选择" filterable>
            <el-option
              v-for="(item,index) in fifthOptions"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用文件:" label-width="100px" class="snElsx" prop="address">
          <div class=" addPut">
            <el-input autocomplete="off" disabled placeholder="请点击上传，上传apk件" style="flex:1" v-model="addForm.url"></el-input>
            <!-- <el-upload class="upload-demo dlePut" style="top:0;right:10px" :action="`${uploadLink}api/apkAdmin`" accept=".APK" :data="pdfData" :show-file-list="false" name="apk" :on-progress="beforeAvatarUpload" :on-success="handleSuccess">
              <el-button class="" round size="mini">上传{{videoFlag ? '' : videoUploadPercent + '%'}}</el-button>
            </el-upload> -->
            <el-upload class="upload-demo dlePut apkBtn" action="#" id="file" :auto-upload="false" :show-file-list="false" :on-change="apkFile">
              <el-button class="" round size="mini">上传{{videoFlag ? '' : goodsData + '%'}}</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="名称:" label-width="100px" prop="app_name">
          <el-input v-model="addForm.app_name" class="add_select" placeholder="请输入名称" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="应用包名:" label-width="100px" prop="package">
          <el-input v-model="addForm.package" class="add_select" placeholder="请输入应用包名"></el-input>
        </el-form-item>
        <el-form-item label="版本号:" label-width="100px" prop="version_name">
          <el-input v-model="addForm.version_name" class="add_select" placeholder="请输入版本号" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="内部版本号:" label-width="100px" prop="version_code">
          <el-input v-model.number="addForm.version_code" class="add_select" placeholder="请输入内部版本号" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="更新描述:" label-width="100px" prop="desc">
          <el-input maxlength="100" show-word-limit autocomplete="off" placeholder="请输入更新描述" type="textarea" class="add_select" v-model="addForm.desc" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" @click.native="getaddAppUpdate('ruleForm')" size="mini" round>确 定</el-button>
        <el-button v-else type="primary" @click.native="geteditAppUpdate('ruleForm')" size="mini" round>编辑</el-button>
      </div>
    </el-dialog>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { queryAppUpdate, addAppUpdate, deleteAppUpdate, queryIdAppUpdate, editAppUpdate } from "@/api/appUpdate.js";
import deleteDialog from "@/components/deleteDialog";
import { ossupload, ossImage } from '@/utils/ossUpload.js'
import readMachine from 'app-info-parser'
import BMF from 'browser-md5-file'
import jszip from 'jszip'
import { mapState } from 'vuex'
import {getNameCode} from "@/api/appUpdate";
export default {
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      checkboxVal: ["名称", "型号", "应用包名", "版本号", "内部版本号", "下载地址", "更新描述", "应用大小", "更新时间"],
      key: 1,
      colData: [], //动态控制table
      //归属table
      browserTable: [],
      total: 0,
      searchTable: "",
      select: "", //搜索条件
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      addForm: { app_name: '', package: '', version_name: '', version_code: '', url: '', desc: '', app_md5: '', size: '', type: 1, sn_three_four: '', sn_five:'' },
      rules: {
        app_name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        package: [{ required: true, message: "请输入应用包名", trigger: "blur" }],
        version_name: [{ required: true, message: "请输入版本号", trigger: "blur" }],
        version_code: [{ required: true, message: "请输入内部版本号" , trigger: "blur"}],
        url: [{ required: true, message: "请上传应用文件", trigger: "blur" }],
        desc: [{ required: true, message: "请输入更新描述", trigger: "blur" }],
        sn_three_four: [{ required: true, message: "请选择类型", trigger: "blur" }],
        sn_five: [{ required: true, message: "请选择sn第五位", trigger: "blur" }],
      },
      //进度条
      videoUploadPercent: 0,
      videoFlag: true,
      pdfData: { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip") },
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), app_name: undefined, package: undefined, version_name: undefined, version_code: undefined },
      uploadLink: process.env.VUE_APP_BASE_API,
      nameCodeOptions: [],
      fifthOptions: [],
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal);//转为数组对象，好控制table
    this.getqueryAppUpdate()
    this.getNameCode();
  },
  computed: {
    ...mapState({//获取上传滚动条
      goodsData: state => state.user.progress
    })
  },
  methods: {
    //获取型号名称
    getNameCode() {
      getNameCode({userId: localStorage.getItem("id")}).then(res => {
        this.nameCodeOptions = res.data.nameCode
        this.fifthOptions = res.data.fifth
      }).catch(err => {
        this.nameCodeOptions = []
        this.fifthOptions = []
      })

    },
    //获取md5
    apkMd5(file) {
      const bmf = new BMF()
      bmf.md5(file, (err, md5) => {//获取文件MD5
        this.addForm.app_md5 = md5
        console.log('md5 string:', err, md5)
      });
    },
    apkFile(event) {
      var filePath = event.name //文件名
      var index = filePath.lastIndexOf(".");
      var ext = filePath.substr(index + 1);
      this.addForm.size = event.size
      var supportFileTypes = ['ipa', 'apk', 'xapk'];
      var splits = (event.name || event).split('.');
      var fileType = splits[splits.length - 1].toLowerCase();
      if (!supportFileTypes.includes(fileType)) return this.$message.error('请上传正确的文件格式')
      const parser = new readMachine(event.raw)
      this.videoFlag = false;
      this.apkMd5(event.raw)//获取文件MD5
      ossupload(event.raw, filePath, true, event.size).then(res => {
        this.videoFlag = true;
        this.addForm.url = res
        this.$store.commit('user/SET_PROGRESS', 0)
        //文件类型
        if (ext == 'xapk') {//xapk
          this.getXapkInfo(parser);
        } else {
          parser.parse().then(res => {//apk
            this.addForm.package = res.package;
            this.addForm.version_name = res.versionName;
            this.addForm.version_code = res.versionCode;
            this.addForm.app_name = (res.application.label).constructor == Array ? res.application.label[0] : res.application.label;
          }).catch(err => {
            this.$message.error('无法识别文件格式, 请重新上传')
          })
        }
      }).catch(err => {
        this.videoFlag = true;
        this.$store.commit('user/SET_PROGRESS', 0)
        err.code == 10086 ? this.$message(err.msg) : ''
        //上传oss失败关闭弹窗，4个异步任务，无法结束
        this.dialogFormVisible = false
      })
    },
    //获取xapk信息
    getXapkInfo(parser, type) {
      const xapk = parser
      let file = xapk.file;
      let blob = new Blob([file]);
      jszip.loadAsync(blob, { optimizedBinaryString: true }).then(res => {
        for (let key in res.files) {
          //判断是否是目录
          if (!res.files[key].dir) {
            //找到我们压缩包所需要的json文件
            if (/\.(json)$/.test(res.files[key].name)) {
              res.file(res.files[key].name).async('string').then(item => {
                //得到我们需要的JSON文件内容
                let infocontent = JSON.parse(item);
                this.addForm.package = infocontent.package_name;
                this.addForm.version_name = infocontent.version_name;
                this.addForm.version_code = infocontent.version_code;;
                this.addForm.app_name = infocontent.name;
              })
            }
          }
        }
      }).catch(err => {
        console.log('zpi失败', err)
      });
    },
    //删除
    getappUpdateDel(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      let params = { id: this.deleteDialogs.deleteId }
      deleteAppUpdate(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryAppUpdate()
      })
    },
    //编辑
    geteditAppUpdate(fromName) {
      this.$refs[fromName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.userId = localStorage.getItem("ID")
          addForm.id = this.subjectId
          editAppUpdate(addForm).then(res => {
            this.$message.success('修改成功')
            this.getqueryAppUpdate()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    getqueryIdAppUpdate(id) {
      this.editSubjects = false
      this.subjectId = id
      let params = { id: id }
      queryIdAppUpdate(params).then(res => {
        this.dialogFormVisible = true
        Object.keys(this.addForm).forEach(key => { this.addForm[key] = res.data[key] })
      })
    },
    //添加
    getaddAppUpdate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.userId = localStorage.getItem("ID")
          addAppUpdate(addForm).then(res => {
            this.$message.success('添加成功')
            this.getqueryAppUpdate()
            this.dialogFormVisible = false
          }).catch(err => {
            // this.getqueryAppUpdate()
            err.code == 400 ? this.$message.error(err.msg) : ''
          })
        } else {
          return false
        }
      })
    },
    beforeAvatarUpload(event) {
      this.apkUnplate = false;//将添加和上传的按钮分开
      this.videoFlag = false;
      this.videoUploadPercent = Math.floor(event.percent)
    },
    handleSuccess(res) {
      if (res.code == 200) {
        // this.videoUploadPercent = 100;
        console.log('返回的参数', res.data)
        setTimeout(() => {
          this.videoUploadPercent = 0;
          this.videoFlag = true
          this.addForm.url = res.data.filePath
          this.addForm.app_name = res.data.appName
          this.addForm.package = res.data.bg
          this.addForm.version_name = res.data.versionName;
          this.addForm.version_code = res.data.versionCode;
          this.addForm.size = res.data.size;
          this.addForm.app_md5 = res.data.md5;
        }, 500)
      } else {
        this.$message.error(res.msg)
        this.videoUploadPercent = 0;
        this.videoFlag = true
      }
    },
    getqueryAppUpdate() {
      queryAppUpdate(this.listQuery).then(res => {
        this.browserTable = res.data
        this.total = res.total
        console.log('成功', res.data)
      }).catch(err => {
        this.browserTable = []
        this.total = 0
      })
    },
    btnaddBrand() {
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryAppUpdate(1, val);
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryAppUpdate(val);
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = this.$options.data().addForm
      })
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), app_name: undefined, package: undefined, version_name: undefined, version_code: undefined }
      this.getqueryAppUpdate()
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.download {
  display: inline-block;
  height: 30px;
  width: 30px;
  line-height: 30px;
  background-color: #f4f4f4;
  box-shadow: none;
  border: 1px solid #ccc;
  border-left: 0;
  border-radius: 2px;
  position: relative;
  a {
    position: absolute;
    top: 0;
    left: 0;
    display: inline-block;
    height: 30px;
    width: 30px;
  }
}
</style>
